package com.witmore.skyline.web.service;

import com.witmore.skyline.web.config.MqttConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.MessageChannel;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class MqttService {

    // Neutron 业务配置
    @Autowired
    @Qualifier("neutronOutboundChannel")
    private MessageChannel neutronOutboundChannel;

    // WeChat 业务配置
    @Autowired
    @Qualifier("wechatOutboundChannel")
    private MessageChannel wechatOutboundChannel;

    @Autowired
    private MqttConfig mqttConfig;

    public void sendMessage(Integer orgId, String payload) {
        log.info("企业：{} 发送消息到MQTT，消息内容：{}", orgId, payload);
        try {
            String topic = mqttConfig.buildNeutronTopic(orgId.toString());
            log.info("Sending message to MQTT topic: {}, payload: {}", topic, payload);
            neutronOutboundChannel.send(MessageBuilder.withPayload(payload)
                    .setHeader(MqttHeaders.TOPIC, topic)
                    .setHeader("business", "neutron")
                    .build());
        } catch (Exception e) {
            log.error("发送消息到MQTT失败，error msg-->{}, e", e.getMessage(), e);
        }

    }

    public void sendWeChatMessage(String payload) {
        log.info("发送企微群消息到MQTT，消息内容：{}", payload);
        try {
            wechatOutboundChannel.send(MessageBuilder.withPayload(payload)
                    .setHeader(MqttHeaders.TOPIC, mqttConfig.getWechatTopic())
                    .setHeader("business", "wechat")
                    .build());
        } catch (Exception e) {
            log.error("发送企微群消息到MQTT失败 -->{}, e", e.getMessage(), e);
        }
    }
}